import React, { useState, memo, useEffect } from 'react';
import { Table, Dialog, Button, Row, MessagePlugin, Alert } from 'tdesign-react';
import SearchForm from './components/SearchForm';
import EditDialog from './components/EditDialog';
import './index.module.less';
import classnames from 'classnames';
import CommonStyle from '@/styles/common.module.less';
import { useLocation } from 'react-router-dom';
import PubSub from 'pubsub-js'
import { deleteUserAPI, getUserAllListAPI } from '@/api/user.api';
import Tag from 'tdesign-react/es/tag/Tag';

type AlignType = 'left' | 'center' | 'right';
type FixedType = 'left' | 'right';

export const SelectTable = () => {
  // 获取当前路由地址
  const location = useLocation();
  const listPath = location.pathname.split('/').pop();
  // pub-sub 发布当前的路由
  PubSub.publish('listPath', listPath);
  const [userList, setUserList] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([0, 1]);
  const [visible, setVisible] = useState(false);
  const [editVisible, setEditVisible] = useState(false);
  const [currentUser, setCurrentUser] = useState<any>(null);
  // 搜索和排序参数state
  const [searchParams, setSearchParams] = useState({
    page: 1,
    pageSize: 3,
    role: '',
    sortOrder: 'ASC',
    sortBy: 'studentId',
    searchText: '',
  });

  // 搜索表单提交
  const handleSearch = async (values: any) => {
    setSearchParams(prev => ({
      ...prev,
      ...values,
      searchText: values.searchText || '',
      page: 1, // 搜索时重置到第一页
    }));
  };
  const fetchUserList = () => {
    getUserAllListAPI({
      page: searchParams.page,
      pageSize: searchParams.pageSize,
      role: searchParams.role,
      sortOrder: searchParams.sortOrder,
      sortBy: searchParams.sortBy,
      searchText: searchParams.searchText,
    }).then(res => {
      // 适配后端返回的 list 数据结构
      const list = res.data.data.list || [];
      setUserList(list.map((item: any) => ({
        studentId: item.user?.studentId || item.studentId || '',
        name: item.user?.name || item.name || '',
        gender: item.user?.gender || item.gender || '',
        role: item.user?.role || item.role || '',
        phone: item.user?.phone || item.phone || '',
        email: item.user?.email || item.email || '',
        departmentName: item.user?.departmentName || item.departmentName || '',
        // 其他字段按需补充
      })));
      setTotal(res.data.data.total || 0);
    }).finally(() => setLoading(false));
  }
  // 排序、分页、筛选联动
  useEffect(() => {
    setLoading(true);
    fetchUserList()
  }, [searchParams]);

  // 分页、排序事件
  const handlePageChange = (current: number, pageInfo: any) => {
    setSearchParams(prev => ({
      ...prev,
      page: pageInfo.current,
      pageSize: pageInfo.pageSize,
    }));
  };
  const handleSortChange = (sort: any) => {
    if (sort && sort.length > 0) {
      setSearchParams(prev => ({
        ...prev,
        sortBy: sort[0].sortBy,
        sortOrder: sort[0].desc ? 'DESC' : 'ASC',
      }));
    }
  };
  const [deleteId, setDeleteId] = useState('');
  useEffect(() => {
    return () => {
      // dispatch(clearPageState());
    };
  }, []);
  // 选择
  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }

  // 重新处理点击操作
  function handleClickEdit(record: any) {
    setCurrentUser(record.row);
    setEditVisible(true);
  }

  // 编辑成功回调
  function handleEditSuccess() {
    fetchUserList();
  }

  // 删除
  function handleClickDelete(record: any) {
    setDeleteId(record.row.studentId);
    setVisible(true);
  }
  // 关闭弹窗
  function handleClose() {
    setVisible(false);
  }
  // 确认删除
  function handleConfirmDelete() {
    deleteUserAPI(deleteId).then(res => {
      if (res.status === 200) {
        MessagePlugin.success('删除成功');
        setDeleteId('');
        setVisible(false);
        fetchUserList()
      } else {
        MessagePlugin.error('删除失败');
      }
    })
  }
  // 用户管理表格列
  const userColumns = [
    {
      title: '学号',
      align: 'left' as AlignType,
      width: 140,
      colKey: 'studentId',
    },
    {
      title: '姓名',
      align: 'left' as AlignType,
      width: 100,
      colKey: 'name',
    },
    {
      title: '性别',
      align: 'center' as AlignType,
      width: 80,
      colKey: 'gender',
      cell({ row }: any) {
        return row.gender === 'male' ? '男' : row.gender === 'female' ? '女' : row.gender;
      },
    },
    {
      title: '身份',
      align: 'center' as AlignType,
      width: 100,
      colKey: 'role',
      cell({ row }: any) {
        return row.role === 'admin' ? <Tag theme="success" variant="light">管理员</Tag> : row.role === 'student' ? <Tag theme='warning' variant='light'>学生</Tag> : <Tag theme='primary' variant='light'>教师</Tag>;
      },
    },
    {
      title: '手机号',
      align: 'center' as AlignType,
      width: 140,
      colKey: 'phone',
    },
    {
      title: '邮箱',
      align: 'left' as AlignType,
      width: 160,
      colKey: 'email',
    },
    {
      title: '部门',
      align: 'left' as AlignType,
      width: 160,
      colKey: 'departmentName',
    },
    {
      align: 'center' as AlignType,
      fixed: 'right' as FixedType,
      width: 180,
      colKey: 'op',
      title: '操作',
      cell(record: any) {
        return (
          <>
            <Button
              theme='primary'
              variant='text'
              onClick={() => {
                handleClickEdit(record);
              }}
            >
              编辑
            </Button>
            <Button
              theme='primary'
              variant='text'
              onClick={() => {
                handleClickDelete(record);
              }}
            >
              删除
            </Button>
          </>
        );
      },
    },
  ];
  return (
    <>
      <Row justify='start' style={{ marginBottom: '20px' }}>
        <SearchForm
          onSubmit={handleSearch}
          onCancel={() => setSearchParams({ ...searchParams, role: '' })}
        />
      </Row>
      <Table
        loading={loading}
        data={userList}
        columns={userColumns}
        rowKey='studentId'
        selectedRowKeys={selectedRowKeys}
        hover
        onSelectChange={onSelectChange}
        pagination={{
          pageSize: searchParams.pageSize,
          total,
          current: searchParams.page,
          showJumper: true,
          pageSizeOptions: [3, 5, 8, 10],
          onCurrentChange: handlePageChange,
          onPageSizeChange: (size) => handlePageChange(1, { current: 1, pageSize: size }),
        }}
        sort={{
          sortBy: searchParams.sortBy,
          descending: searchParams.sortOrder === 'DESC',
        }}
        onSortChange={handleSortChange}
      />
      <EditDialog
        visible={editVisible}
        onClose={() => setEditVisible(false)}
        onSuccess={handleEditSuccess}
        userData={currentUser}
      />
      <Dialog header='确认删除当前用户？' visible={visible} onClose={handleClose} onConfirm={handleConfirmDelete}>
        <Alert message="删除后当前用户的所有信息将会被删除且无法恢复" theme='error' />
      </Dialog>
    </>
  );
};

const selectPage: React.FC = () => (
  <div className={classnames(CommonStyle.pageWithPadding, CommonStyle.pageWithColor)}>
    <SelectTable />
  </div>
);

export default memo(selectPage);
